class_name AIBehavior
extends Node

const DURATION_AI_TICK_FREQUENCY = 200

var time_sine_last_tick := 0
var player: Player
var ball: Ball
var opponent_detection_area: Area2D
var teammate_detection_area: Area2D

func _ready() -> void:
	time_sine_last_tick = Time.get_ticks_msec() + randi_range(0, DURATION_AI_TICK_FREQUENCY)
	
func setup(context_player: Player, context_ball: Ball, context_opponent_detection_area: Area2D, context_teammate_detection_area: Area2D) -> void:
	player = context_player
	ball = context_ball
	opponent_detection_area = context_opponent_detection_area
	teammate_detection_area = context_teammate_detection_area
	
func process_ai() -> void:
	if Time.get_ticks_msec() - time_sine_last_tick > DURATION_AI_TICK_FREQUENCY:
		time_sine_last_tick = Time.get_ticks_msec()
		process_ai_movement()
		process_ai_decision()
	
func process_ai_movement() -> void:
	pass
	
func process_ai_decision() -> void:
	pass
	
func get_bicircular_weight(position: Vector2, center_target: Vector2, inner_circule_radius: float, inner_circule_weight: float, outside_circule_radius: float, outside_circule_weight: float) -> float:
	var distance_to_center := position.distance_to(center_target)
	if distance_to_center > outside_circule_radius:
		return outside_circule_weight
	elif distance_to_center < inner_circule_radius:
		return inner_circule_weight
	else:
		var distance_inner_radius := distance_to_center - inner_circule_radius
		var close_range_radius := outside_circule_radius - inner_circule_radius
		return lerpf(inner_circule_weight, outside_circule_weight, distance_inner_radius / close_range_radius)
		
func is_ball_carried_by_teammate() -> bool:
	return ball.carried != null && ball.carried != player && ball.carried.country == player.country
	
func is_ball_possessed_by_opponent() -> bool:
	return ball.carried != null && ball.carried.country != player.country

func has_opponent_nearby() -> bool:
	var players := opponent_detection_area.get_overlapping_bodies()
	return players.find_custom(func(p: Player): return p.country != player.country) != -1
	
func has_teammate_in_view() -> bool:
	var players := teammate_detection_area.get_overlapping_areas()
	return players.find_custom(func(p: Player): return p.country == player.country) != -1
